package com.ts.conch.auth.exception;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.lang.Dict;
import com.ts.conch.common.result.CommonResult;
import com.ts.conch.common.utils.HttpServletRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.ValidationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GlobalExceptionHandler
 * @Decription: 自定义全局异常处理策略
 * @Author: IDai
 * @Date: 2021-09-15 11:52 星期三
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /** 日志打印工具 **/
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResult<?> handleRRException(BusinessException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("业务异常", e);
        return CommonResult.failed(e.getCode() + "", e.getMsg());
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public CommonResult<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("方法参数类型不匹配", e);
        return CommonResult.failed(400 ,"方法参数类型不匹配", "");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("缺少请求参数", e);
        return CommonResult.failed(400,"缺少请求参数", "");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("参数解析失败", e);
        return CommonResult.failed(400,"参数解析失败", "");
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public CommonResult<?> handleValidationException(ValidationException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("参数验证失败", e);
        return CommonResult.failed(400,"参数验证失败","");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult<?> handleHttpRequestMethodNotSupportedException(   HttpRequestMethodNotSupportedException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("不支持当前请求方法", e);
        return CommonResult.failed(405,"不支持当前请求方法", "");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public CommonResult<?> handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error("不支持当前媒体类型", e);
        return CommonResult.failed(415,"不支持当前媒体类型", "");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public CommonResult<?> handleDuplicateKeyException(DuplicateKeyException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error(e.getMessage(), e);
        return CommonResult.failed("数据库中已存在该记录");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public CommonResult<?> handleMaxSizeException(MaxUploadSizeExceededException e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error(e.getMessage(), e);
        return CommonResult.failed("File too large!");
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NotLoginException.class)
    public CommonResult<?> handleNotLoggerInException(NotLoginException e, HttpServletResponse response) throws IOException {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error(e.getMessage(), e);
        return CommonResult.failed(401, e.getMessage(), "");
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(SaTokenException.class)
    public CommonResult<?> handleMaxSizeException(SaTokenException e, HttpServletResponse response) throws IOException {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error(e.getMessage(), e);
        return CommonResult.failed(403, e.getMessage(), "");
    }

    /**
     * 验证bean类型
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        List<Map> result = new ArrayList<>();
        e.getBindingResult().getFieldErrors().forEach((fieldError) -> {
            result.add(Dict.create().set("field", fieldError.getField()).set("msg", fieldError.getDefaultMessage()));
        });
        return CommonResult.failed(result);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResult<?> handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return CommonResult.failed(404, "路径不存在，请检查路径是否正确","");
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<?> handleException(Exception e) {
        logger.info(HttpServletRequestUtil.getAllRequestInfo());
        logger.error(e.getMessage(), e);
        return CommonResult.failed(500, "服务器异常","");
    }
}
